package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ApiServiceImpl implements ApiService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AdChannelFeign adChannelFeign;

    @Override
    public List<AdChannel> fainAll() {
        //从redis获取
        String channelListJsonList = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);
        List<AdChannel> channelList = null;
        if (!StringUtils.isEmpty(channelListJsonList)){
            channelList = JSON.parseArray(channelListJsonList, AdChannel.class);
        }
        if (StringUtils.isEmpty(channelListJsonList)){
            ResultVo<List<AdChannel>> listResultVo = adChannelFeign.listAll();
            if (!listResultVo.isSuccess()){
                throw new LeadNewsException("后台查询列表失败");
            }
            channelList = listResultVo.getData();
            stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST,JSON.toJSONString(channelList));
        }
        return channelList;


    }
}
